package com.java.zhuiyun.api.dict_navigation_tabs.controller;

import com.java.zhuiyun.api.dict_navigation_tabs.entity.SysDictPc;
import com.java.zhuiyun.api.dict_navigation_tabs.service.DictNavigationTabsService;
import com.java.zhuiyun.api.sys_dict.entity.SysDict;
import com.java.zhuiyun.common.response.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DictNavigationTabsController
 * @Description TODO PC导航标签
 * @Author WX
 * @Date 2023/8/21 20:50
 **/
@RestController
@RequestMapping("/dictNavigation")
@CrossOrigin
public class DictNavigationTabsController {
    @Autowired
    private DictNavigationTabsService dictNavigationTabsService;

    /**
     * @ClassName DictNavigationTabsController
     * @Description TODO PC导航标签
     * @Author WX
     * @Date 2023/8/21 20:50
     **/
    @RequestMapping("/navigationTabs")
    public CommonResult navigationTabs(){
        List<SysDictPc> sysDictPcS = dictNavigationTabsService.navigationTabs();
        List<SysDictPc> treeData = convertToTree(sysDictPcS);
        return CommonResult.ok(treeData);
    }

    /*
    * @Author WX
    * @Description 输出树状结构
    * @Date 2023/8/31 10:22
    * @Return
    * @param null
    */
    private List<SysDictPc> convertToTree(List<SysDictPc> data) {
        Map<Integer, SysDictPc> nodes = new HashMap<>();
        List<SysDictPc> tree = new ArrayList<>();

        // 将所有数据构建成以 id 为键的哈希表
        for (SysDictPc item : data) {
            nodes.put(item.getId(), item);
        }

        // 遍历数据构建树状结构
        for (SysDictPc item : data) {
            Integer prentId = item.getPrentId();

            if (prentId == null) {
                // 如果父级 id 为空，则将该数据作为根节点的一部分，并添加到树的顶层
                tree.add(item);
            } else {
                // 如果父级 id 不为空，则找到对应的数据节点，判断子节点数量是否已满
                SysDictPc prentNode = nodes.get(prentId);
                if (prentNode != null) {
                    List<SysDictPc> children = prentNode.getChildren();
                    if (children.size() < 2) {
                        children.add(item);
                    }
                }
            }
        }

        return tree;
    }
}
